package com.usian.admin.service.impi;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sun.org.apache.regexp.internal.RE;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WmNewsFeign;
import com.usian.admin.service.AdChannelService;
import com.usian.admin.service.AdSensitiveService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.aliyun.GreenTextScan;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsVo;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {
    @Autowired
    private WmNewsFeign wmNewsFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Value("${fileServerUrl}")
    private String imageUrl;

    @Autowired
    private AdChannelService adChannelService;

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Autowired
    private AdSensitiveService adSensitiveService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;




    /***
     * 文章审核
     * @param id
     */
    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {
        try {

            //1:校验参数
            if (id==null){
                log.info("审核文章id为空");
                return;
            }
            //2:查找文章信息
            WmNews wmNews = wmNewsFeign.findById(id);
            if (wmNews==null){
                log.error("审核的自媒体文章不存在，自媒体的id:{}", id);
            }
            // status==4 人工审核通过待发布
            if (wmNews.getStatus()==4){
                //维护三个表 并改状态为9
                this.saveArticle(wmNews);
                return;
            }
            // status==8 需要发布 待发布
            if (wmNews.getStatus()==8&&wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
                //维护三个表 并改状态为9
                this.saveArticle(wmNews);
                return;
            }

            //3:判断状态 人工审核 status
            //status==1 待审核
            if (wmNews.getStatus()==1){
                Map<String, Object> handle = this.handleTextAndImages(wmNews);
                Map map = greenTextScan.greeTextScan(handle.get("content").toString());
                //pass通过 block 不通过 review 不确定
                if (!map.get("suggestion").equals("pass")){
                    if (map.get("suggestion").equals("block")){
                        //修改状态为2失败
                        this.updateWmnews(wmNews,(short)2,"阿里云文本审核不通过");
                    }if (map.get("suggestion").equals("review")){
                        //修改状态为3不确定
                        this.updateWmnews(wmNews,(short)3,"阿里云文本审核结果不确定");
                    }
                }
                //审核图片
                List<String> imageList =(List<String> )handle.get("image");
                List<byte[]>imageByte=new ArrayList<>();
                for (String image : imageList) {
                    //group/Moo/1/3/2/ccc.jpg
                    String imageName = image.replace(imageUrl, "");
                    int index = imageName.indexOf("/");
                    String groupName = imageName.substring(0, index);
                    String url = imageName.substring(index + 1);
                    byte[] bytes = fastDFSClientUtil.download(groupName, url);
                    imageByte.add(bytes);
                }
                Map imageMap = greenImageScan.imageScan(imageByte);
                if (!imageMap.get("suggestion").equals("pass")){
                    if (imageMap.get("suggestion").equals("block")){
                        //修改状态为2失败
                        this.updateWmnews(wmNews,(short)2,"阿里云图片审核不通过");
                    }if (imageMap.get("suggestion").equals("review")){
                        //修改状态为3不确定
                        this.updateWmnews(wmNews,(short)3,"阿里云图片审核结果不确定");
                    }
                }

                //4:调用阿里云审核敏感词
                List<String> allSensitive = adSensitiveService.findAllSensitive();
                SensitiveWordUtil.initMap(allSensitive);
                Map<String, Integer> words = SensitiveWordUtil.matchWords(handle.get("content").toString());
                if (words.size()>0){
                    this.updateWmnews(wmNews,(short)2,"文本敏感词审核不通过");
                }
                //如果全通过 发布时间>当前时间 8待发布
                if (wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                    this.updateWmnews(wmNews,(short)8,"审核通过,发布时间还没到");
                }
                //5:文章信息维护到3个文章表 更新wmnews发布时间<当前审核时间 status ==9 已发布
                this.saveArticle(wmNews);

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //文章人工审核 查询列表
    @Override
    public PageResponseResult findNews(NewsAuthDto dto) {
        PageResponseResult responseResult =  wmNewsFeign.findList(dto);
        //有图片需要显示，需要fasfdfs服务器地址
        responseResult.setHost(imageUrl);
        return responseResult;
    }
    //文章人工审核
    @Override
    public ResponseResult findOne(Integer id) {
        //分页查询
        WmNewsVo wmNewsVo = wmNewsFeign.findWmNewsVo(id);
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(imageUrl);
        return responseResult;
    }

    //文章人工审核 修改状态
    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {
        //校验参数
        if (type==null || dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews news = wmNewsFeign.findById(dto.getId());
        if (news!=null){
            //type=1 通过 type=0 失败
            if (type.equals(1)){
                this.updateWmnews(news,(short) 4,"审核通过");
            }else {
                this.updateWmnews(news,(short) 2,dto.getMsg());
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }


    private void  saveArticle(WmNews wmNews){
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());
        //获取作者相关信息
        //1:保存主表 ap_article
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wmNewsFeign.findWmUserById(userId.longValue());
        if (wmUser!=null){
            ApAuthor apAuthor = articleFeign.findByName(wmUser.getName());
            if (apAuthor!=null){
                apArticle.setAuthorId(apAuthor.getId().longValue());
                apArticle.setAuthorName(apAuthor.getName());
            }
        }
        //获取频道信息
        Integer channelId = wmNews.getChannelId();
        AdChannel channel = adChannelService.getOne(Wrappers.<AdChannel>lambdaQuery().eq(AdChannel::getId, channelId));
        if (channel!=null){
            apArticle.setChannelId(channel.getId());
            apArticle.setChannelName(channel.getName());
        }
        ApArticle apArticle1 = articleFeign.saveArticle(apArticle);

        //2:保存内容表ap_article_content

        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle1.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);

        //3:保存文章配置表 ap_article_config
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle1.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);
        articleFeign.saveArticleConfig(apArticleConfig);

        //4:修改wmnews status==9
        if (wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
            this.updateWmnews(wmNews,(short)9,"审核通过");
            Map<String,Object>map =new HashMap<>();
            map.put("id",apArticle.getId().toString());
            map.put("publishTime",apArticle.getPublishTime());
            map.put("layout",apArticle.getLayout());
            map.put("images",apArticle.getImages());
            map.put("authorId",apArticle.getAuthorId());
            map.put("title",apArticle.getTitle());
            map.put("content",wmNews.getContent());
            IndexRequest indexRequest=new IndexRequest("app_init_article").id(apArticle1.getId().toString()).source(map);
            try {
                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else{
            this.updateWmnews(wmNews,(short)8,"审核通过,待发布");

        }
    }

    //修改文章状态
    public void updateWmnews(WmNews wmNews,Short status ,String msg){
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wmNewsFeign.update(wmNews);
    }

    //分离文章中的文本和图片
    private Map<String,Object> handleTextAndImages(WmNews wmNews){
        //存储文本内容
        StringBuilder sb=new StringBuilder();
        //存放图片
        List<String> images = new ArrayList<>();

        //处理文章内容
        String content = wmNews.getContent();
        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        for (Map map : contentList) {
            if (map.get("type").equals("text")){
                sb.append(map.get("value"));
            }
            if (map.get("type").equals("image")){
                images.add((String)map.get("value"));
            }
        }
        //处理文章封面
        if (wmNews.getImages()!=null){
            String[] strings = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(strings));
            //加进去的元素在遍历时删除会报错 原因ArrayList和对象本身不是一个集合
        }
        //分离文本和图片后封装成map集合
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("content",sb.toString());
        resultMap.put("image" ,images);
        return resultMap;
    }
}
